package edu.cs.cse461.android;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Properties;

import org.json.JSONException;
import org.json.JSONObject;

import edu.cs.cse461.android.R;
import edu.uw.cs.cse461.sp12.OS.OS;
import edu.uw.cs.cse461.sp12.OS.RPCCallerSocket;
import edu.uw.cs.cse461.sp12.OS.RPCService;
import edu.uw.cs.cse461.sp12.utilIP.MyContext;
import android.app.Activity;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PingAppActivity extends Activity {
	
	private TextView ipField;
			
	public static String ipAddress;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	MyContext.context = this;
        setContentView(R.layout.main);
        ipField = ((TextView)findViewById(R.id.ipText));
        ipField.setText("");
        
        WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int wifiIPInt = wifiInfo.getIpAddress();
        String wifiIP = Formatter.formatIpAddress(wifiIPInt);
        ipAddress = wifiIP;
        
        ipField.setText(ipAddress);
        
        
        
        
    }
    
    @Override
    public void onStart(){
    	super.onStart();
    	
    	
        
        //localPort.setText(msg);
		
        new Thread(){
            public void run() {
              // worker thread starts running asynchronously here
            	String configFilename = "foo.bar.config.ini";
                Properties config = new Properties();
                try {
        			config.load(getAssets().open(configFilename));
        			OS.boot(config);
        			OS.startServices(OS.rpcServiceClasses);
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} catch (Exception e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
              runOnUiThread(new Runnable() {
                public void run() {
                  // main thread runs this code
                	String msg = Integer.toString(((RPCService)OS.getRPCService("rpc")).localPort());
                	
                	try {
						String ip = ((RPCService)OS.getRPCService("rpc")).localIP();
						TextView localIP = ((TextView)findViewById(R.id.ipText));
	                    localIP.setText(msg);
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
                    TextView localPort = ((TextView)findViewById(R.id.localPort));
                    localPort.setText(msg);
                }
              });
            }
          }.start();
    }
    
    
        
    
    public void runPing(View view) {
    	Log.i("pingapp", "gets here3");
    	new Thread(new Runnable() {
            public void run() {
            	TextView host = ((TextView)findViewById(R.id.host));
            	TextView port = ((TextView)findViewById(R.id.port));
            	long startTime = System.currentTimeMillis();
				RPCCallerSocket socket;
				long totalTime = 0;
				try {
					Log.i("pingapp", port.getText().toString());
					socket = new RPCCallerSocket(host.getText().toString(), host.getText().toString(), port.getText().toString());
					JSONObject response = socket.invoke("echo", "echo", new JSONObject().put("", "") );
					totalTime = System.currentTimeMillis() - startTime;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} //TODO: Check to see if the socket should be created before starting the timer
				catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				final String time = totalTime + "";
				runOnUiThread(new Runnable() {
			        public void run() {
			          // main thread runs this code
			        	TextView pingResult = ((TextView)findViewById(R.id.pingResult));
			        	pingResult.setText(time);
			        }
			      });
            	
            }
        }).start();
    }
}